package com.wnhz.work.yz.fragment.bathroomdetails;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.meiqia.meiqiasdk.third.photoview.PhotoView;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.activity.BathroomDetailActivity;
import com.wnhz.work.yz.adapter.MyViewPagerAdapter;
import com.wnhz.work.yz.base.BaseFragment;
import com.wnhz.work.yz.bean.BathroomDetail2Bean;
import com.wnhz.work.yz.bean.BathroomDetailBean;
import com.wnhz.work.yz.utils.AddImages;
import com.wnhz.work.yz.view.ExpandTextView;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * ---概括
 */
public class ProbablyFragment extends BaseFragment implements View.OnClickListener {
    private View view;
    public BathroomDetailBean bean;
    private TextView tv_title, repertory_tv, tv_price;
    private ExpandTextView tv_action;

    public BathroomDetailBean getBean() {
        return bean;
    }

    private ViewPager viewPager;
    private LinearLayout indicatorLayout;
    private MyViewPagerAdapter bannerAdapter;

    private ArrayList<View> viewList = new ArrayList<>();// 添加了首尾的轮播图集合
    private List<String> autoPlayImages = new ArrayList<>();// 轮播图的图片资源集合
    private int currentPosition;
    private PhotoView[] indicators;

    private WebView webview;

    public void setBean(BathroomDetailBean bean) {
        this.bean = bean;
        Log.i(TAG, "setBean:=== " + bean.toString());
        initView();

    }

    public void setBean2(BathroomDetail2Bean bean) {
        this.bean.setBanner(bean.getBanner().get(0));

        Log.i(TAG, "setBean:=== " + bean.toString());
        initView();
    }

    private BathroomDetailActivity activity;
    private static final String TAG = "ProbablyFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_probably, container, false);
        activity = (BathroomDetailActivity) getActivity();
        return view;
    }

    private void initView() {
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_action = (ExpandTextView) view.findViewById(R.id.tv_action);
        repertory_tv = (TextView) view.findViewById(R.id.repertory_tv);
        tv_price = (TextView) view.findViewById(R.id.tv_price);

        viewPager = (ViewPager) view.findViewById(R.id.homePager_viewpager);
        indicatorLayout = (LinearLayout) view.findViewById(R.id.homepager_indicator);
        webview = (WebView) view.findViewById(R.id.webview);
        view.findViewById(R.id.ll_search).setOnClickListener(this);
        tv_title.setText(bean.getGoods_name());
        if (bean.getIs_activity().equals("1")) {
            tv_action.setVisibility(View.VISIBLE);
            tv_action.setText(bean.getActivity_tips());
        } else {
            tv_action.setVisibility(View.GONE);
        }
        repertory_tv.setText(bean.getGoods_des());
        if ("1".equals(bean.getCan_buy())) {
            tv_price.setText("市场指导价:¥" + bean.getDetail_price());
        } else {
            tv_price.setText("零售价:" + bean.getOprice());
        }

        autoPlayImages.add(bean.getBanner());
        initViewPager();
        setViewPager();
        bannerAdapter.notifyDataSetChanged();

        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(false);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        if (webview != null) {
            webview.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    handler.sendEmptyMessage(1);
                    super.onPageFinished(view, url);
                }
            });
//            webview.getSettings().setJavaScriptEnabled(true);
            webview.loadUrl(bean.getDetail_url());
        }
    }

    private void initViewPager() {

        int indicatorSize = autoPlayImages.size();

        indicators = new PhotoView[indicatorSize];

        for (int i = 0; i < indicators.length; i++) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_indicator, null);
            indicators[i] = (PhotoView) view.findViewById(R.id.image_indicator);
            indicatorLayout.addView(view);
        }

        viewList = AddImages.addImageDatas(getActivity(), autoPlayImages, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = (int) v.getTag();
            }
        });

        bannerAdapter = new MyViewPagerAdapter(viewList);
        viewPager.setAdapter(bannerAdapter);
        if (indicators.length > 1) {
            viewPager.setCurrentItem(1, false);
        }

    }

    private void setViewPager() {
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                currentPosition = arg0;
                if (currentPosition < 1) { // 首位之前，跳转到末尾（N）
                    setIndicator(autoPlayImages.size() - 1);
                } else if (currentPosition > autoPlayImages.size()) { // 末位之后，跳转到首位（1）
                    setIndicator(0);
                } else {

                    setIndicator(currentPosition - 1);
                }

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                if (arg0 == 0) {
                    handler.removeMessages(11);
                    Message message = new Message();
                    message.what = 11;
                    handler.sendMessageDelayed(message, 3000);
                    viewPager.setCurrentItem(currentPosition, false);
                    if (viewList.size() > 1) { // 多于1，才会循环跳转
                        if (currentPosition < 1) { // 首位之前，跳转到末尾（N）
                            currentPosition = autoPlayImages.size(); // 注意这里是mList，而不是mViews
                            viewPager.setCurrentItem(currentPosition, false);
                        } else if (currentPosition > autoPlayImages.size()) { // 末位之后，跳转到首位（1）
                            viewPager.setCurrentItem(currentPosition, true); // false:不显示跳转过程的动画
                            viewPager.setCurrentItem(1, false); // false:不显示跳转过程的动画
                            currentPosition = 1;
                        }

                    }
                }

            }
        });

        currentPosition = 1;
        setIndicator(0);
        viewPager.setCurrentItem(currentPosition, false);
        handler.removeMessages(11);
        Message message = new Message();
        message.what = 11;
        handler.sendMessageDelayed(message, 3000);
    }

    /**
     * 设置指示器
     *
     * @param selectedPosition 默认指示器位置
     */
    private void setIndicator(int selectedPosition) {


        for (int i = 0; i < indicators.length; i++) {
            indicators[i].setBackgroundResource(R.drawable.icon_point);
        }
        if (indicators.length > selectedPosition)
            indicators[selectedPosition].setBackgroundResource(R.drawable.icon_point_pre);
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 11:
//                    Toast.makeText(getActivity(),currentPosition+"",Toast.LENGTH_LONG).show();
                    int position = currentPosition + 1;
                    viewPager.setCurrentItem(position, true);
                    break;

                case 1:
//                    activity.closeDialog();
                    break;

                default:
                    break;
            }
        }

    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_search:
//                MyToast("分享");

                break;
        }
    }

}
